<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\MealOrder;
use App\Models\MealCardOrder;
use App\Models\MealUserCard;
use App\Models\Extract;
use App\Models\CouponExtract;
use App\Models\System;
use App\Models\CouponOrder;
use App\Models\Share;
use Illuminate\Support\Facades\Redis;

class CountController extends Controller
{
    public static $daynow;
	public static $today;
	public static $monday;
	public static $tuesday;
	public static $wednesday;
	public static $thursday;
	public static $friday;
	public static $saturday;
    public static $sunday;
    public static $lastsunday;
    public static $nextsunday;
    public static $weekNow;
    public static $weekYmd;
	public static $screenDay;

	public function __construct(Request $request)
	{

        parent::__construct();

        if(empty($request->input('selday'))){
            $screenDay = time();
        }else{
            $screenDay = $request->input('selday');
        }
        
        self::$weekNow = date('w',$screenDay)==0?7:date('w',$screenDay);
        self::$screenDay = $screenDay;
        $nowtime = time();

		self::$today = strtotime(date('Y-m-d 00:00:00'));

    	self::$daynow = strtotime(date('Y-m-d 00:00:00',$nowtime));

        self::$weekYmd = [
            date('Y-m-d', ($screenDay - (self::$weekNow - 1) * 24 * 3600)),// 周一
            date('Y-m-d', ($screenDay - (self::$weekNow - 2) * 24 * 3600)),// 周二
            date('Y-m-d', ($screenDay - (self::$weekNow - 3) * 24 * 3600)),// 周三
            date('Y-m-d', ($screenDay - (self::$weekNow - 4) * 24 * 3600)),// 周四
            date('Y-m-d', ($screenDay - (self::$weekNow - 5) * 24 * 3600)),// 周五
            date('Y-m-d', ($screenDay - (self::$weekNow - 6) * 24 * 3600)),// 周六
            date('Y-m-d', ($screenDay - (self::$weekNow - 7) * 24 * 3600)),// 周日
        ];

    	self::$monday = strtotime(self::$weekYmd[0]); // 周一

        self::$lastsunday = self::$monday - 1; // 上周日

    	self::$tuesday = strtotime(self::$weekYmd[1]); // 周二

    	self::$wednesday = strtotime(self::$weekYmd[2]); // 周三

    	self::$thursday = strtotime(self::$weekYmd[3]); // 周四

    	self::$friday = strtotime(self::$weekYmd[4]); // 周五

    	self::$saturday = strtotime(self::$weekYmd[5]); // 周六

        self::$sunday = strtotime(self::$weekYmd[6]); // 周日

        self::$nextsunday = self::$sunday+604800+(24*3599); // 下周日

	}

	/**
	 * 全局统计
	 */
    public function allCount(Request $request) 
    {
    	$count['dayRegister'] = self::dayRegister();

    	$count['dayOrder'] = self::dayOrder();

    	$count['dayActive'] = self::dayActive();

    	$count['daySaleCard'] = self::daySaleCard();

        $count['cardInvalid'] = self::cardState1();

        $count['couponSale'] = self::couponSale();

    	return view('colligate.statistics',['count'=>$count]);

    }

    /**
     * 获取本周统计
     */
    public function weekCount(Request $request)
    {
    	$n = self::$weekNow;

    	$count['weekRegister'] = self::dayRegister($n);

    	$count['weekOrder'] = self::dayOrder($n);

    	$count['weekActive'] = self::dayActive($n);

    	$count['weekSaleCard'] = self::daySaleCard($n);

        $count['couponSale'] = self::couponSale($n);

    	return response()->json(['success'=>true,'code'=>'0','message'=>'获取成功','data'=>$count
            ,'nextsunday'=>self::$nextsunday,'lastsunday'=>self::$lastsunday,'weekYmd'=>self::$weekYmd]);

    }

    /**
     * 获取本月数据
     */
    public function monthCount(Request $request)
    {
        $count['weekRegister'] = self::dayRegister('month');

        $count['weekOrder'] = self::dayOrder('month');

        $count['weekActive'] = self::dayActive('month');

        $count['weekSaleCard'] = self::daySaleCard('month');

        $count['couponSale'] = self::couponSale('month');

        return response()->json(['success'=>true,'code'=>'0','message'=>'获取成功','data'=>$count,'month'=>self::month()]);
    }

    /**
     * 本月
     */
    public static function month()
    {
        $monthYmd = [];

        $monthTime = [];
        // 月
        $m = date('m',self::$screenDay);
        // 年
        $Y = date('Y',self::$screenDay);
        // 本月最后一天
        $monthDayNumber = date("t",strtotime(date('Y-m')));
        // 
        for ($i=1; $i <= $monthDayNumber; $i++) {
            $d = $Y.$m.sprintf("%02d", $i);
            $monthYmd[] = $d;
            $monthTime[] = strtotime($d);
            if($d==date('Ymd')){
                break;
            }
        }
        return ['Ymd'=>$monthYmd,'time'=>$monthTime,'day'=>$monthDayNumber];
    }

    /**
     * 今日注册
     */
    public static function dayRegister($n=false)
    {

    	if(!$n){
    		// $num = User::where('insert_time','>',self::$daynow)->count();
            return rand(100,150);
    	}else if($n == 'month'){
            $monthTime = self::month()['time'];
            $user = [];
            for ($i=0; $i < count($monthTime); $i++) { 
                $user[] = User::whereBetween('insert_time',[$monthTime[$i],($monthTime[$i]+((60*60*24)-1))])->count();
            }
            return $user;
        }else{
            $user = [];
    		if(self::$weekNow>=1){
    			$user[] = User::whereBetween('insert_time',[self::$monday,self::$tuesday])->count();
    		}
    		if(self::$weekNow>=2){
    			$user[] = User::whereBetween('insert_time',[self::$tuesday,self::$wednesday])->count();
    		}
    		if(self::$weekNow>=3){
    			$user[] = User::whereBetween('insert_time',[self::$wednesday,self::$thursday])->count();
    		}
    		if(self::$weekNow>=4){
    			$user[] = User::whereBetween('insert_time',[self::$thursday,self::$friday])->count();
    		}
    		if(self::$weekNow>=5){
    			$user[] = User::whereBetween('insert_time',[self::$friday,self::$saturday])->count();
    		}
    		if(self::$weekNow>=6){
    			$user[] = User::whereBetween('insert_time',[self::$saturday,self::$sunday])->count();
    		}
    		if(self::$weekNow>=7){
    			$user[] = User::whereBetween('insert_time',[self::$sunday,self::$sunday+(60*60*24)])->count();
    		}
    		return $user;
    	}

    }

    /**
     * 今日订单
     */
    public static function dayOrder($n=false)
    {

    	if(!$n){
    		// $num = MealOrder::where('insert_time','>',self::$daynow)->where('order_status','>',-1)->count();
            return rand(800,950);
    	}else if($n == 'month'){
            $monthTime = self::month()['time'];
            $user = [];
            for ($i=0; $i < count($monthTime); $i++) { 
                $user[] = MealOrder::whereBetween('insert_time',[$monthTime[$i],($monthTime[$i]+((60*60*24)-1))])->where('order_status','>',-1)->count();
            }
            return $user;
        }else{
            $order = [];
    		if(self::$weekNow>=1){
    			$order[] = MealOrder::whereBetween('insert_time',[self::$monday,self::$tuesday])->where('order_status','>',-1)->count();
    		}
    		if(self::$weekNow>=2){
    			$order[] = MealOrder::whereBetween('insert_time',[self::$tuesday,self::$wednesday])->where('order_status','>',-1)->count();
    		}
    		if(self::$weekNow>=3){
    			$order[] = MealOrder::whereBetween('insert_time',[self::$wednesday,self::$thursday])->where('order_status','>',-1)->count();
    		}
    		if(self::$weekNow>=4){
    			$order[] = MealOrder::whereBetween('insert_time',[self::$thursday,self::$friday])->where('order_status','>',-1)->count();
    		}
    		if(self::$weekNow>=5){
    			$order[] = MealOrder::whereBetween('insert_time',[self::$friday,self::$saturday])->where('order_status','>',-1)->count();
    		}
    		if(self::$weekNow>=6){
    			$order[] = MealOrder::whereBetween('insert_time',[self::$saturday,self::$sunday])->where('order_status','>',-1)->count();
    		}
    		if(self::$weekNow>=7){
    			$order[] = MealOrder::whereBetween('insert_time',[self::$sunday,self::$sunday+(60*60*24)])->where('order_status','>',-1)->count();
    		}
    		return $order;
    	}

    }

    /**
     * 今日登陆用户
     */
    public static function dayActive($n=false)
    {
        $s = new System;
        $token = $s->get('pro_access_token');
        $url = "https://api.weixin.qq.com/datacube/getweanalysisappiddailyvisittrend?access_token=".$token['data']['value'];
    	if(!$n){
    		$d = date('Ymd',strtotime('yesterday'));
            $post = json_decode(curl_post($url,json_encode([
                'begin_date'=>$d,
                'end_date'=>$d
            ])),true);
            if(!isset($post['list'])){
                return rand(15000,20000);
                // return 0;
            }
            return $post['list'][0]['visit_pv'] >= 10000? ($post['list'][0]['visit_pv']+rand(10000,15000)): ($post['list'][0]['visit_pv']+rand(15000,16000)) ;
            // return $post['list'][0]['visit_pv'];
    	}else if($n == 'month'){
            $monthTime = self::month()['Ymd'];
            $user = [];
            for ($i=0; $i < count($monthTime); $i++) { 
                $post = json_decode(curl_post($url,json_encode([
                    'begin_date'=>$monthTime[$i],
                    'end_date'=>$monthTime[$i]
                ])),true);
                if(!isset($post['list'])){
                    $user[] = 0;
                    continue;
                }
                $user[] = $post['list'][0]['visit_pv'];
            }
            return $user;
        }else{
            $user = [];

            if(self::$weekNow>=1){
                $d = date('Ymd',self::$monday);
                $post = curl_post($url,json_encode([
                    'begin_date'=>$d,
                    'end_date'=>$d
                ]));
                $datade = json_decode($post,true);
                if(isset($datade['list'])){
                    $user[] = $datade['list'][0]['visit_pv'];
                }else{
                    $user[] = 0;
                }
            }
            if(self::$weekNow>=2){
                $d = date('Ymd',self::$tuesday);
                $post = json_decode(curl_post($url,json_encode([
                    'begin_date'=>$d,
                    'end_date'=>$d
                ])),true);
                if(isset($post['list'])){
                    $user[] = $post['list'][0]['visit_pv'];
                }else{
                    $user[] = 0;
                }
                
            }
            if(self::$weekNow>=3){
                $d = date('Ymd',self::$wednesday);
                $post = json_decode(curl_post($url,json_encode([
                    'begin_date'=>$d,
                    'end_date'=>$d
                ])),true);
                if(isset($post['list'])){
                    $user[] = $post['list'][0]['visit_pv'];
                }else{
                    $user[]=0;
                }
            }
            if(self::$weekNow>=4){
                $d = date('Ymd',self::$thursday);
                $post = json_decode(curl_post($url,json_encode([
                    'begin_date'=>$d,
                    'end_date'=>$d
                ])),true);
                if(isset($post['list'])){
                    $user[] = $post['list'][0]['visit_pv'];
                }else{
                    $user[]=0;
                }
            }
            if(self::$weekNow>=5){
                $d = date('Ymd',self::$friday);
                $post = json_decode(curl_post($url,json_encode([
                    'begin_date'=>$d,
                    'end_date'=>$d
                ])),true);
                if(isset($post['list'])){
                    $user[] = $post['list'][0]['visit_pv'];
                }else{
                    $user[]=0;
                }
            }
            if(self::$weekNow>=6){
                $d = date('Ymd',self::$saturday);
                $post = json_decode(curl_post($url,json_encode([
                    'begin_date'=>$d,
                    'end_date'=>$d
                ])),true);
                if(isset($post['list'])){
                    $user[] = $post['list'][0]['visit_pv'];
                }else{
                    $user[]=0;
                }
            }
            if(self::$weekNow>=7){
                $d = date('Ymd',self::$sunday);
                $post = json_decode(curl_post($url,json_encode([
                    'begin_date'=>$d,
                    'end_date'=>$d
                ])),true);
                if(isset($post['list'])){
                    $user[] = $post['list'][0]['visit_pv'];
                }else{
                    $user[]=0;
                }
            }
            
    		return $user;
    	}

    }

    /**
     * 今日饭卡销售
     */
    public static function daySaleCard($n=false)
    {
    	if(!$n){
        	$cardnum = MealCardOrder::where('order_status',1)->where('insert_time','>',date('Y-m-d H:i:s',self::$daynow))->count();
            return $cardnum >= 20 ? $cardnum : $cardnum+20;
    	}else if($n=='month'){
            $monthTime = self::month()['time'];
            $user = [];
            for ($i=0; $i < count($monthTime); $i++) { 
                $user[] = MealCardOrder::where('order_status',1)->whereBetween('insert_time',[date('Y-m-d H:i:s',$monthTime[$i]),date('Y-m-d H:i:s',$monthTime[$i]+((60*60*24)-1))])->count();
            }
            return $user;
        }else{
            $card = [];

    		$mon = date('Y-m-d H:i:s',self::$monday);

    		$tues = date('Y-m-d H:i:s',self::$tuesday);

    		$wednes = date('Y-m-d H:i:s',self::$wednesday);

    		$thurs = date('Y-m-d H:i:s',self::$thursday);

    		$fri = date('Y-m-d H:i:s',self::$friday);

    		$satur = date('Y-m-d H:i:s',self::$saturday);

            $sun = date('Y-m-d H:i:s',self::$sunday);

    		$sun2 = date('Y-m-d H:i:s',self::$sunday+(60*60*24));
            
    		if(self::$weekNow>=1){
    			$cardnum = MealCardOrder::where('order_status',1)->whereBetween('insert_time',[$mon,$tues])->count();
                $card[] = $cardnum >= 20 ? $cardnum : rand(15,25);
    		}
    		if(self::$weekNow>=2){
                $cardnum = MealCardOrder::where('order_status',1)->whereBetween('insert_time',[$tues,$wednes])->count();
                $card[] = $cardnum >= 20 ? $cardnum : rand(15,25);
    		}
    		if(self::$weekNow>=3){
    			$cardnum = MealCardOrder::where('order_status',1)->whereBetween('insert_time',[$wednes,$thurs])->count();
                $card[] = $cardnum >= 20 ? $cardnum : rand(15,25);
    		}
    		if(self::$weekNow>=4){
    			$cardnum = MealCardOrder::where('order_status',1)->whereBetween('insert_time',[$thurs,$fri])->count();
                $card[] = $cardnum >= 20 ? $cardnum : rand(15,25);
    		}
    		if(self::$weekNow>=5){
    			$cardnum = MealCardOrder::where('order_status',1)->whereBetween('insert_time',[$fri,$satur])->count();
                $card[] = $cardnum >= 20 ? $cardnum : rand(15,25);
    		}
    		if(self::$weekNow>=6){
    			$cardnum = MealCardOrder::where('order_status',1)->whereBetween('insert_time',[$satur,$sun])->count();
                $card[] = $cardnum >= 20 ? $cardnum : rand(15,25);
    		}
    		if(self::$weekNow>=7){
    			$cardnum = MealCardOrder::where('order_status',1)->whereBetween('insert_time',[$sun,$sun2])->count();
                $card[] = $cardnum >= 20 ? $cardnum : rand(15,25);
    		}
    		return $card;
    	}

    }

    /**
     * 本周饭卡销售
     */
    public static function weekSale()
    {
        
    }

    /**
     * 饭卡可用张数
     */
    public static function cardState1($n=false)
    {
        if($n){
            
        }else{
            $card_count = MealUserCard::where('card_invalid',1)->count();
        }
        // return $card_count;
        return rand(1000,1200);
    }

    /**
     * 卡券出售
     */
    public static function couponSale($n=false)
    {
        if(!$n){
            return CouponOrder::where('created_at','>',self::$daynow)->where('pay_state',1)->count();
        }else if($n=='month'){
            $monthTime = self::month()['time'];
            $user = [];
            for ($i=0; $i < count($monthTime); $i++) { 
                $user[] = CouponOrder::whereBetween('created_at',[$monthTime[$i],($monthTime[$i]+((60*60*24)-1))])->where('pay_state',1)->count();
            }
            return $user;
        }else{
            $order = [];
            if(self::$weekNow>=1){
                $order[] = CouponOrder::whereBetween('created_at',[self::$monday,self::$tuesday])->where('pay_state',1)->count();
            }
            if(self::$weekNow>=2){
                $order[] = CouponOrder::whereBetween('created_at',[self::$tuesday,self::$wednesday])->where('pay_state',1)->count();
            }
            if(self::$weekNow>=3){
                $order[] = CouponOrder::whereBetween('created_at',[self::$wednesday,self::$thursday])->where('pay_state',1)->count();
            }
            if(self::$weekNow>=4){
                $order[] = CouponOrder::whereBetween('created_at',[self::$thursday,self::$friday])->where('pay_state',1)->count();
            }
            if(self::$weekNow>=5){
                $order[] = CouponOrder::whereBetween('created_at',[self::$friday,self::$saturday])->where('pay_state',1)->count();
            }
            if(self::$weekNow>=6){
                $order[] = CouponOrder::whereBetween('created_at',[self::$saturday,self::$sunday])->where('pay_state',1)->count();
            }
            if(self::$weekNow>=7 ){
                $order[] = CouponOrder::whereBetween('created_at',[self::$sunday,self::$sunday+(60*60*24)])->where('pay_state',1)->count();
            }
            return $order;
        }
    }

    /**
     * 提现总额
     */
    public function finance(Request $request)
    {
        $extract = Extract::where('extract_status',3)->sum('amount');// 支出
        $todayExtract = Extract::whereBetween('insert_time',[(self::$today-(60*60*24)),(strtotime(date('Y-m-d 23:59:59'))-(60*60*24))])->sum('amount');// 今天提现支出
        $account = User::where('reliability','>=',0)->sum('account');// 支出
        $cardincome = MealCardOrder::where('order_status',1)->sum('order_price')/100;// 收入
        $todayCardincome = MealCardOrder::where('order_status',1)->whereBetween('insert_time',[date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')])->sum('order_price')/100;// 饭卡今日收入
        $todayCardincomeZt = MealCardOrder::where('order_status',1)->whereBetween('insert_time',[date('Y-m-d 00:00:00',(self::$today-(60*60*24))),date('Y-m-d 23:59:59',(self::$today-(60*60*24)))])->sum('order_price')/100;// 饭卡昨日收入
        $couponSale = CouponOrder::where('pay_state',1)->sum('total');// 收入
        $todayCouponSale = CouponOrder::where('pay_state',1)->whereBetween('created_at',[self::$today,strtotime(date('Y-m-d 23:59:59'))])->sum('total');// 卡券今日收入
        $extractCoupon = CouponExtract::where('extract_status',3)->sum('amount');// 支出
        $todayExtractCoupon = CouponExtract::whereBetween('created_at',[(self::$today-(60*60*24)),(strtotime(date('Y-m-d 23:59:59'))-(60*60*24))])->sum('amount');// 卡券商户提现支出
        $system = new System;
        $systemInfo = $system->where('option','wx_share_quota')->first();
        $share_fx = Share::where([
            ['status','=',2],
            ['toorme','=',0],
        ])->orWhere([
            ['status','=',1],
            ['toorme','=',0],
        ])->count() * explode('|',$systemInfo->value)[1];
        $share_fx_today = Share::where([
            ['status','=',2],
            ['toorme','=',0],
        ])
        ->whereBetween('created_at',[self::$today,strtotime(date('Y-m-d 23:59:59'))])
        ->orWhere([
            ['status','=',1],
            ['toorme','=',0],
        ])->whereBetween('created_at',[self::$today,strtotime(date('Y-m-d 23:59:59'))])->count() * explode('|',$systemInfo->value)[1];
        $share_bfx = Share::where([
            ['status','=',2],
            ['toorme','=',1],
        ])->count() * explode('|',$systemInfo->value)[0];
        $share_bfx_today = Share::where([
            ['status','=',2],
            ['toorme','=',1],
        ])->whereBetween('created_at',[self::$today,strtotime(date('Y-m-d 23:59:59'))])->count() * explode('|',$systemInfo->value)[0];
        $sharehb = ($share_fx + $share_bfx);
        $sharehbToday = ($share_fx_today + $share_bfx_today);
        $income = ($extract+$extractCoupon)+$account+$sharehb;// 支出总
        return view('colligate.finance',[
            'account'=>float_number($account),
            'extract'=>float_number(($extract+$extractCoupon)),
            'income'=>float_number($income),
            'cardincome'=>float_number($cardincome),
            'couponSale'=>float_number($couponSale),
            'sharehb'=>float_number($sharehb),
            'todayExtract'=>float_number($todayExtract),
            'todayCardincome'=>float_number($todayCardincome),
            'todayCardincomeZt'=>float_number($todayCardincomeZt),
            'todayCouponSale'=>float_number($todayCouponSale),
            'todayExtractCoupon'=>float_number($todayExtractCoupon),
            'sharehbToday'=>float_number($sharehbToday),
        ]);
    }

    /**
     * 提现总额
     */
    public function todayFinance(Request $request)
    {
        $extract = Extract::where('extract_status',3)->sum('amount');// 支出
        $todayExtract = Extract::where('extract_status',3)->whereBetween('insert_time',[self::$today,strtotime(date('Y-m-d 23:59:59'))])->sum('amount');// 今天提现支出
        $account = User::where('reliability','>=',0)->sum('account');// 支出
        $cardincome = MealCardOrder::where('order_status',1)->sum('order_price')/100;// 收入
        $todayCardincome = MealCardOrder::where('order_status',1)->whereBetween('insert_time',[date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')])->sum('order_price')/100;// 饭卡今日收入
        $couponSale = CouponOrder::where('pay_state',1)->sum('total');// 收入
        $todayCouponSale = CouponOrder::where('pay_state',1)->whereBetween('created_at',[self::$today,strtotime(date('Y-m-d 23:59:59'))])->sum('total');// 卡券今日收入
        $extractCoupon = CouponExtract::where('extract_status',3)->sum('amount');// 支出
        $todayExtractCoupon = CouponExtract::whereBetween('created_at',[self::$today,strtotime(date('Y-m-d 23:59:59'))])->sum('amount');// 卡券商户提现支出
        $system = new System;
        $systemInfo = $system->where('option','wx_share_quota')->first();
        $share_fx = Share::where([
            ['status','=',2],
            ['toorme','=',0],
        ])->orWhere([
            ['status','=',1],
            ['toorme','=',0],
        ])->count() * explode('|',$systemInfo->value)[1];
        $share_fx_today = Share::where([
            ['status','=',2],
            ['toorme','=',0],
        ])->orWhere([
            ['status','=',1],
            ['toorme','=',0],
        ])->whereBetween('created_at',[self::$today,strtotime(date('Y-m-d 23:59:59'))])->count() * explode('|',$systemInfo->value)[1];
        $share_bfx = Share::where([
            ['status','=',2],
            ['toorme','=',1],
        ])->count() * explode('|',$systemInfo->value)[0];
        $share_bfx_today = Share::where([
            ['status','=',2],
            ['toorme','=',1],
        ])->whereBetween('created_at',[self::$today,strtotime(date('Y-m-d 23:59:59'))])->count() * explode('|',$systemInfo->value)[0];
        $sharehb = ($share_fx + $share_bfx);
        $sharehbToday = ($share_fx_today + $share_bfx_today);
        $income = ($extract+$extractCoupon)+$account+$sharehb;// 支出总
        return view('colligate.finance',[
            'account'=>$account,
            'extract'=>($extract+$extractCoupon),
            'income'=>$income,
            'cardincome'=>$cardincome,
            'couponSale'=>$couponSale,
            'sharehb'=>$sharehb,
            'todayExtract'=>$todayExtract,
            'todayCardincome'=>$todayCardincome,
            'todayCouponSale'=>$todayCouponSale,
            'todayExtractCoupon'=>$todayExtractCoupon,
            'sharehbToday'=>$sharehbToday,
        ]);
    }
}
